<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>管理员主页 - 酒店管理系统</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.7.2/css/all.min.css" rel="stylesheet">
    <style>
        body {
            font-family: 'Inter', sans-serif;
        }

        button {
            transition: all 0.3s ease;
        }

        button:hover {
            transform: scale(1.05);
        }

        .merchant-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }

        .merchant-table th, .merchant-table td {
            border: 1px solid #ddd;
            padding: 8px;
            text-align: left;
        }

        .merchant-table th {
            background-color: #f2f2f2;
        }

        .password-cell {
            font-family: monospace;
        }
    </style>
</head>

<body class="bg-gray-100 p-8">
<div class="container mx-auto bg-white p-6 rounded-lg shadow-md">
    <h1 class="text-3xl font-bold mb-6 text-center text-gray-800">管理员主页</h1>
    <div class="flex flex-wrap gap-4 justify-center mb-6">
        <button id="viewMerchantInfo" class="px-6 py-3 bg-blue-600 text-white rounded-md shadow hover:bg-blue-700">
            <i class="fa-solid fa-store mr-2"></i>查看商家信息
        </button>
        <button id="viewUserInfo" class="px-6 py-3 bg-green-600 text-white rounded-md shadow hover:bg-green-700">
            <i class="fa-solid fa-user mr-2"></i>查看用户信息
        </button>
        <button id="reviewShopApplication" class="px-6 py-3 bg-yellow-600 text-white rounded-md shadow hover:bg-yellow-700">
            <i class="fa-solid fa-clipboard-check mr-2"></i>审核店铺入驻平台的申请
        </button>
        <button id="reviewTenantRecharge" class="px-6 py-3 bg-orange-600 text-white rounded-md shadow hover:bg-orange-700">
            <i class="fa-solid fa-money-bill-transfer mr-2"></i>审核租户充值信息
        </button>
        <button id="statisticsUserSignIn" class="px-6 py-3 bg-teal-600 text-white rounded-md shadow hover:bg-teal-700">
            <i class="fa-solid fa-chart-bar mr-2"></i>统计用户签到信息
        </button>
    </div>

    <!-- 商家信息表格区域 -->
    <div id="merchantInfoSection" class="hidden mt-6">
        <h2 class="text-xl font-bold mb-4 text-gray-700">商家信息列表</h2>
        <div class="overflow-x-auto">
            <table id="merchantTable" class="merchant-table">
                <thead>
                <tr>
                    <th>商家ID</th>
                    <th>商家名称</th>
                    <th>地址</th>
                    <th>成立年份</th>
                    <th>联系方式</th>
                    <th>关键词</th>
                    <th>营业状态</th>
                    <th>申请状态</th>
                    <th>销量</th>
                    <th>收藏数</th>
                    <th>营业额</th>
                    <th>操作</th>
                </tr>
                </thead>
                <tbody id="merchantTableBody">
                <!-- 商家数据将在这里动态生成 -->
                </tbody>
            </table>
        </div>
    </div>

    <!-- 其他现有区域 -->
    <div id="pendingRechargesSection" class="hidden">
        <h2 class="text-xl font-bold mb-4 text-gray-700">待审核充值信息</h2>
        <table id="pendingRechargesTable" class="w-full border-collapse border border-gray-300">
            <thead>
            <tr>
                <th class="border border-gray-300 px-4 py-2 bg-gray-200">钱包ID</th>
                <th class="border border-gray-300 px-4 py-2 bg-gray-200">用户ID</th>
                <th class="border border-gray-300 px-4 py-2 bg-gray-200">充值金额</th>
                <th class="border border-gray-300 px-4 py-2 bg-gray-200">充值原因</th>
                <th class="border border-gray-300 px-4 py-2 bg-gray-200">操作</th>
            </tr>
            </thead>
            <tbody></tbody>
        </table>
    </div>
</div>
<!-- 用户信息表格区域 -->
<div id="userInfoSection" class="hidden mt-6">
    <h2 class="text-xl font-bold mb-4 text-gray-700">用户信息列表</h2>
    <div class="overflow-x-auto">
        <table id="userTable" class="merchant-table">
            <thead>
            <tr>
                <th>用户ID</th>
                <th>用户名</th>
                <th>性别</th>
                <th>年龄</th>
                <th>生日</th>
                <th>用户状态</th>
                <th>操作</th>
            </tr>
            </thead>
            <tbody id="userTableBody">
            <!-- 用户数据将在这里动态生成 -->
            </tbody>
        </table>
    </div>
</div>
<!-- 审核店铺入驻申请区域 -->
<div id="shopApplicationSection" class="hidden mt-6">
    <h2 class="text-xl font-bold mb-4 text-gray-700">待审核的店铺入驻申请</h2>
    <div class="overflow-x-auto">
        <table id="applicationTable" class="merchant-table">
            <thead>
            <tr>
                <th>商家ID</th>
                <th>商家名称</th>
                <th>地址</th>
                <th>成立年份</th>
                <th>联系方式</th>
                <th>关键词</th>
                <th>操作</th>
            </tr>
            </thead>
            <tbody id="applicationTableBody">
            <!-- 申请数据将在这里动态生成 -->
            </tbody>
        </table>
    </div>
</div>
<!-- 用户签到信息统计区域 -->
<div id="userSignInStatisticsSection" class="hidden mt-6">
    <h2 class="text-xl font-bold mb-4 text-gray-700">用户签到信息统计</h2>
    <div class="overflow-x-auto">
        <table id="userSignInTable" class="merchant-table">
            <thead>
            <tr>
                <th>用户ID</th>
                <th>总积分</th>
                <th>连续签到天数</th>
                <th>累计签到天数</th>
            </tr>
            </thead>
            <tbody id="userSignInTableBody">
            <!-- 用户签到数据将在这里动态生成 -->
            </tbody>
        </table>
    </div>
</div>
<script>
    document.addEventListener("DOMContentLoaded", function () {
        // 查看商家信息按钮点击事件
        document.getElementById("viewMerchantInfo").addEventListener("click", function () {
            const merchantInfoSection = document.getElementById('merchantInfoSection');
            merchantInfoSection.classList.toggle('hidden');

            if (!merchantInfoSection.classList.contains('hidden')) {
                // 调用获取商家信息的API
                fetchMerchantInfo();
            }
        });

        // 查看用户信息按钮点击事件
        document.getElementById("viewUserInfo").addEventListener("click", function () {
            const userInfoSection = document.getElementById('userInfoSection');
            userInfoSection.classList.toggle('hidden');

            if (!userInfoSection.classList.contains('hidden')) {
                // 调用获取用户信息的API
                fetchUserInfo();
            }
        });

        // 审核店铺入驻申请按钮点击事件
        document.getElementById("reviewShopApplication").addEventListener("click", function () {
            const shopApplicationSection = document.getElementById('shopApplicationSection');
            shopApplicationSection.classList.toggle('hidden');

            if (!shopApplicationSection.classList.contains('hidden')) {
                // 调用获取待审核申请的API
                fetchPendingApplications();
            }
        });

        document.getElementById("reviewTenantRecharge").addEventListener("click", function () {
            const pendingRechargesSection = document.getElementById('pendingRechargesSection');
            pendingRechargesSection.classList.toggle('hidden');

            if (!pendingRechargesSection.classList.contains('hidden')) {
                fetch('/GetPendingRechargesServlet')
                   .then(response => response.json())
                   .then(data => {
                        const tableBody = document.querySelector('#pendingRechargesTable tbody');
                        tableBody.innerHTML = '';
                        data.forEach(recharge => {
                            const row = document.createElement('tr');
                            row.innerHTML = `
                                <td class="border border-gray-300 px-4 py-2">${recharge.walletId}</td>
                                <td class="border border-gray-300 px-4 py-2">${recharge.userId}</td>
                                <td class="border border-gray-300 px-4 py-2">${recharge.topUpAmount}</td>
                                <td class="border border-gray-300 px-4 py-2">${recharge.rechargeReason}</td>
                                <td class="border border-gray-300 px-4 py-2">
                                    <button class="px-3 py-1 bg-green-600 text-white rounded hover:bg-green-700" onclick="approveRecharge(${recharge.walletId})">审核通过</button>
                                    <button class="px-3 py-1 bg-red-600 text-white rounded hover:bg-red-700" onclick="rejectRecharge(${recharge.walletId})">审核不通过</button>
                                </td>
                            `;
                            tableBody.appendChild(row);
                        });
                    });
            }
        });

        // 统计用户签到信息按钮点击事件
    document.getElementById("statisticsUserSignIn").addEventListener("click", function () {
        const userSignInStatisticsSection = document.getElementById('userSignInStatisticsSection');
        userSignInStatisticsSection.classList.toggle('hidden');

        if (!userSignInStatisticsSection.classList.contains('hidden')) {
            // 调用获取所有用户积分信息的API
            fetch('/getPointsInfo?action=all')
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应错误');
                    }
                    return response.text();
                })
                .then(data => {
                    try {
                        const pointsList = JSON.parse(data);
                        const tableBody = document.getElementById('userSignInTableBody');
                        tableBody.innerHTML = '';

                        if (pointsList.length === 0) {
                            const emptyRow = document.createElement('tr');
                            emptyRow.innerHTML = '<td colspan="4" class="text-center py-4">没有找到用户签到信息</td>';
                            tableBody.appendChild(emptyRow);
                            return;
                        }

                        // 填充表格数据
                        pointsList.forEach(points => {
                            const row = document.createElement('tr');
                            row.innerHTML = `
                                <td>${points.userId}</td>
                                <td>${points.totalPoints}</td>
                                <td>${points.consecutiveDays}</td>
                                <td>${points.cumulativeDays}</td>
                            `;
                            tableBody.appendChild(row);
                        });
                    } catch (error) {
                        console.error('解析JSON数据出错:', error);
                        const errorRow = document.createElement('tr');
                        errorRow.innerHTML = '<td colspan="4" class="text-center py-4">获取用户签到信息失败，请稍后重试</td>';
                        document.getElementById('userSignInTableBody').appendChild(errorRow);
                    }
                })
                .catch(error => {
                    console.error('获取用户签到信息出错:', error);
                    const errorRow = document.createElement('tr');
                    errorRow.innerHTML = '<td colspan="4" class="text-center py-4">获取用户签到信息失败，请稍后重试</td>';
                    document.getElementById('userSignInTableBody').appendChild(errorRow);
                });
        }
    });
});

    // 获取商家信息的函数
    function fetchMerchantInfo() {
        fetch('/MerchantInfoServlet')
           .then(response => {
                if (!response.ok) {
                    throw new Error('网络响应错误');
                }
                return response.text();
            })
           .then(data => {
                try {
                    // 解析JSON数据
                    const merchants = JSON.parse(data);
                    const tableBody = document.getElementById('merchantTableBody');
                    tableBody.innerHTML = '';

                    if (merchants.length === 0) {
                        const emptyRow = document.createElement('tr');
                        emptyRow.innerHTML = '<td colspan="12" class="text-center py-4">没有找到商家信息</td>';
                        tableBody.appendChild(emptyRow);
                        return;
                    }

                    // 填充表格数据
                    merchants.forEach(merchant => {
                        const row = document.createElement('tr');
                        // 修改状态判断：将"已封禁"改为"黑商"
                        const isBanned = merchant.businessStatus === '黑商';
                        const buttonText = isBanned ? '解除封禁' : '封禁';
                        const buttonClass = isBanned ? 'bg-purple-600' : 'bg-red-600';
                        const buttonIcon = isBanned ? 'fa-unlock' : 'fa-ban';
                        const action = isBanned ? 'unban' : 'ban';

                        row.innerHTML = `
                            <td>${merchant.merchantId}</td>
                            <td>${merchant.merchantName}</td>
                            <td>${merchant.address}</td>
                            <td>${merchant.establishmentYear}</td>
                            <td>${merchant.contactInfo}</td>
                            <td>${merchant.keywords}</td>
                            <td>${merchant.businessStatus}</td>
                            <td>${merchant.applicationStatus}</td>
                            <td>${merchant.salesVolume !== null ? merchant.salesVolume : '-'}</td>
                            <td>${merchant.favoritesCount !== null ? merchant.favoritesCount : '-'}</td>
                            <td>${merchant.turnover !== null ? merchant.turnover : '-'}</td>
                            <td>
                                <button class="px-3 py-1 ${buttonClass} text-white rounded hover:bg-opacity-80"
                                    onclick="toggleMerchantStatus(${merchant.merchantId}, '${action}')">
                                    <i class="fa-solid ${buttonIcon} mr-1"></i>${buttonText}
                                </button>
                            </td>
                        `;
                        tableBody.appendChild(row);
                    });
                } catch (error) {
                    console.error('解析JSON数据出错:', error);
                    const errorRow = document.createElement('tr');
                    errorRow.innerHTML = '<td colspan="12" class="text-center py-4">获取商家信息失败，请稍后重试</td>';
                    document.getElementById('merchantTableBody').appendChild(errorRow);
                }
            })
           .catch(error => {
                console.error('获取商家信息出错:', error);
                const errorRow = document.createElement('tr');
                errorRow.innerHTML = '<td colspan="12" class="text-center py-4">获取商家信息失败，请稍后重试</td>';
                document.getElementById('merchantTableBody').appendChild(errorRow);
            });
    }

    // 其他函数保持不变
    function approveRecharge(walletId) {
        if (confirm('确认要审核通过该充值申请吗？')) {
            fetch(`/ApproveRechargeServlet?walletId=${walletId}`)
               .then(response => response.json())
               .then(data => {
                    if (data.success) {
                        alert('审核通过，充值信息已成功插入账单流水表');
                        // 刷新表格
                        document.getElementById("reviewTenantRecharge").click();
                    } else {
                        alert('审核失败');
                    }
                });
        }
    }

    // 获取用户信息的函数
function fetchUserInfo() {
    fetch('/UserInfoServlet')
        .then(response => {
            if (!response.ok) {
                throw new Error('网络响应错误');
            }
            return response.text();
        })
        .then(data => {
            try {
                const users = JSON.parse(data);
                const tableBody = document.getElementById('userTableBody');
                tableBody.innerHTML = '';

                if (users.length === 0) {
                    tableBody.innerHTML = '<tr><td colspan="7" class="text-center py-4">没有找到用户信息</td></tr>';
                    return;
                }

                users.forEach(user => {
                    const row = document.createElement('tr');
                    // 修改状态判断：增加对"解封中"状态的处理
                    const isBanned = user.userStatus === '黑户';
                    const isProcessing = user.userStatus === '解封中';

                    let buttonText, buttonClass, buttonIcon, action;
                    if (isBanned) {
                        buttonText = '解除封禁';
                        buttonClass = 'bg-purple-600';
                        buttonIcon = 'fa-unlock';
                        action = 'unban';
                    } else if (isProcessing) {
                        buttonText = '设为正常';
                        buttonClass = 'bg-blue-600';
                        buttonIcon = 'fa-check-circle';
                        action = 'normal';
                    } else {
                        buttonText = '设为黑户';
                        buttonClass = 'bg-red-600';
                        buttonIcon = 'fa-user-secret';
                        action = 'ban';
                    }

                    row.innerHTML = `
                        <td>${user.userId}</td>
                        <td>${user.username}</td>
                        <td>${user.gender}</td>
                        <td>${user.age || '-'}</td>
                        <td>${user.birthday || '-'}</td>
                        <td>${user.userStatus}</td>
                        <td>
                            <button class="px-3 py-1 ${buttonClass} text-white rounded hover:bg-opacity-80"
                                onclick="toggleUserStatus(${user.userId}, '${action}')">
                                <i class="fa-solid ${buttonIcon} mr-1"></i>${buttonText}
                            </button>
                        </td>
                    `;
                    tableBody.appendChild(row);
                });
            } catch (error) {
                tableBody.innerHTML = '<tr><td colspan="7" class="text-center py-4">获取用户信息失败</td></tr>';
            }
        })
        .catch(error => {
            tableBody.innerHTML = '<tr><td colspan="7" class="text-center py-4">网络错误，请稍后重试</td></tr>';
        });
}

    // 获取待审核的店铺申请
function fetchPendingApplications() {
    fetch('/PendingShopApplicationsServlet')
        .then(response => response.text())
        .then(data => {
            try {
                const applications = JSON.parse(data);
                const tableBody = document.getElementById('applicationTableBody');
                tableBody.innerHTML = '';

                if (applications.length === 0) {
                    tableBody.innerHTML = '<tr><td colspan="7" class="text-center py-4">没有找到待审核的申请</td></tr>';
                    return;
                }

                applications.forEach(app => {
                    const row = document.createElement('tr');
                    row.innerHTML = `
                        <td>${app.merchantId}</td>
                        <td>${app.merchantName}</td>
                        <td>${app.address}</td>
                        <td>${app.establishmentYear}</td>
                        <td>${app.contactInfo}</td>
                        <td>${app.keywords}</td>
                        <td>
                            <button class="px-3 py-1 bg-green-600 text-white rounded hover:bg-green-700"
                                onclick="approveApplication(${app.merchantId})">通过</button>
                            <button class="px-3 py-1 bg-red-600 text-white rounded hover:bg-red-700"
                                onclick="rejectApplication(${app.merchantId})">拒绝</button>
                        </td>
                    `;
                    tableBody.appendChild(row);
                });
            } catch (error) {
                tableBody.innerHTML = '<tr><td colspan="7" class="text-center py-4">获取申请信息失败，请稍后重试</td></tr>';
            }
        })
        .catch(error => {
            tableBody.innerHTML = '<tr><td colspan="7" class="text-center py-4">网络错误，请稍后重试</td></tr>';
        });
}

// 处理通过申请
function approveApplication(merchantId) {
    if (confirm('确认通过该店铺的入驻申请吗？')) {
        fetch(`/ProcessShopApplicationServlet?action=approve&merchantId=${merchantId}`)
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('申请已通过');
                    // 刷新申请列表
                    fetchPendingApplications();
                } else {
                    alert('操作失败: ' + data.message);
                }
            });
    }
}

// 处理拒绝申请
function rejectApplication(merchantId) {
    if (confirm('确认拒绝该店铺的入驻申请吗？')) {
        fetch(`/ProcessShopApplicationServlet?action=reject&merchantId=${merchantId}`)
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('申请已拒绝');
                    // 刷新申请列表
                    fetchPendingApplications();
                } else {
                    alert('操作失败: ' + data.message);
                }
            });
    }
}

    // 处理拒绝申请
    function rejectApplication(merchantId) {
        if (confirm('确认拒绝该店铺的入驻申请吗？')) {
            fetch(`/ProcessShopApplicationServlet?action=reject&merchantId=${merchantId}`)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        alert('申请已拒绝');
                        // 刷新申请列表
                        fetchPendingApplications();
                    } else {
                        alert('操作失败: ' + data.message);
                    }
                });
        }
    }

    // 处理商家状态切换（封禁/解除封禁）
    function toggleMerchantStatus(merchantId, action) {
        const actionText = action === 'ban' ? '封禁' : '解除封禁';
        if (confirm(`确认要${actionText}该商家吗？`)) {
            fetch(`/ManageMerchantStatusServlet?merchantId=${merchantId}&action=${action}`)
               .then(response => response.json())
               .then(data => {
                    if (data.success) {
                        alert(`${actionText}成功`);
                        // 刷新商家列表
                        fetchMerchantInfo();
                    } else {
                        alert(`${actionText}失败: ${data.message}`);
                    }
                })
               .catch(error => {
                    console.error('操作出错:', error);
                    alert(`${actionText}失败，请稍后重试`);
                });
        }
    }

    // 处理用户状态切换
function toggleUserStatus(userId, action) {
    let actionText;
    if (action === 'ban') {
        actionText = '设为黑户';
    } else if (action === 'unban') {
        actionText = '解除封禁';
    } else if (action === 'normal') {
        actionText = '设为正常';
    }

    if (confirm(`确认要${actionText}该用户吗？`)) {
        fetch(`/ManageUserStatusServlet?userId=${userId}&action=${action}`)
           .then(response => response.json())
           .then(data => {
                if (data.success) {
                    alert(`${actionText}成功`);
                    fetchUserInfo(); // 刷新用户列表
                } else {
                    alert(`${actionText}失败: ${data.message}`);
                }
            })
           .catch(error => {
                console.error('操作出错:', error);
                alert(`${actionText}失败，请稍后重试`);
            });
    }
}
</script>
</body>

</html>